package com.yik;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.*;

public class Main {

    public static List<String> readColumnFromXlsx(String filePath, String columnName) throws IOException {
        List<String> columnData = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(new File(filePath));
             Workbook workbook = new XSSFWorkbook(fis)) {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            // 获取表头行
            Row headerRow = sheet.getRow(0);
            if (headerRow == null) {
                return columnData;
            }
            // 查找指定列名的列索引
            int columnIndex = -1;
            int sourceDepartmentColumnIndex = -1; // 用于存储“数据来源部门”列的索引
            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null && cell.getCellType() == CellType.STRING) {
                    if (cell.getStringCellValue().equals(columnName)) {
                        columnIndex = i;
                    }
                    if (cell.getStringCellValue().equals("数据来源部门")) {
                        sourceDepartmentColumnIndex = i;
                    }
                }
            }
            if (columnIndex == -1) {
                System.out.println("未找到列名: " + columnName);
                return columnData;
            }
            if (sourceDepartmentColumnIndex == -1) {
                System.out.println("未找到列名: 数据来源部门");
                return columnData;
            }
            // 遍历每一行（从第二行开始，跳过表头）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    Cell cell = row.getCell(columnIndex);
                    Cell sourceDepartmentCell = row.getCell(sourceDepartmentColumnIndex);
                    if (cell != null) {
                        boolean shouldAdd = true; // 新增的布尔变量，用于标记是否添加当前行数据
                        if (sourceDepartmentCell != null && sourceDepartmentCell.getCellType() == CellType.STRING) {
                            String sourceDepartment = sourceDepartmentCell.getStringCellValue();
                            if ("信息中心".equals(sourceDepartment) || "医保局".equals(sourceDepartment)) {
                                shouldAdd = false; // 如果数据来源部门是“信息中心”或“医保局”，则不添加
                            }
                        } else {
                            // 如果“数据来源部门”单元格为空，也将其视为可添加数据
                            shouldAdd = true;
                        }
                        if (shouldAdd) {
                            // 根据单元格类型获取值
                            switch (cell.getCellType()) {
                                case STRING:
                                    columnData.add(cell.getStringCellValue());
                                    break;
                                case NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cell)) {
                                        columnData.add(cell.getDateCellValue().toString());
                                    } else {
                                        columnData.add(String.valueOf(cell.getNumericCellValue()));
                                    }
                                    break;
                                case BOOLEAN:
                                    columnData.add(String.valueOf(cell.getBooleanCellValue()));
                                    break;
                                case FORMULA:
                                    columnData.add(cell.getCellFormula());
                                    break;
                                default:
                                    columnData.add("");
                            }
                        }
                    } else {
                        columnData.add("");
                    }
                } else {
                    columnData.add("");
                }
            }
        }
        return columnData;
    }

    // 获取另一个 Word 文件中的所有字符
    public static List<Character> getAllCharactersFromWord(String filePath) throws IOException {
        List<Character> allCharacters = new ArrayList<>();
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
             XWPFDocument document = new XWPFDocument(bis)) {
            // 处理正文段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    String text = run.getText(0);
                    if (text != null) {
                        for (char c : text.toCharArray()) {
                            allCharacters.add(c);
                        }
                    }
                }
            }
            // 处理脚注
            for (XWPFFootnote footnoteDoc : document.getFootnotes()) {
                for (XWPFParagraph paragraph : footnoteDoc.getParagraphs()) {
                    for (XWPFRun run : paragraph.getRuns()) {
                        String text = run.getText(0);
                        if (text != null) {
                            for (char c : text.toCharArray()) {
                                allCharacters.add(c);
                            }
                        }
                    }
                }
            }
            // 处理尾注
            for (XWPFEndnote endnoteDoc : document.getEndnotes()) {
                for (XWPFParagraph paragraph : endnoteDoc.getParagraphs()) {
                    for (XWPFRun run : paragraph.getRuns()) {
                        String text = run.getText(0);
                        if (text != null) {
                            for (char c : text.toCharArray()) {
                                allCharacters.add(c);
                            }
                        }
                    }
                }
            }
            // 处理表格
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            for (XWPFRun run : paragraph.getRuns()) {
                                String text = run.getText(0);
                                if (text != null) {
                                    for (char c : text.toCharArray()) {
                                        allCharacters.add(c);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 处理目录（虽然目录也是段落，但有些特殊格式可能需要额外处理）
            // 这里假设目录已经在段落中被正常处理，如果有特殊需求可以进一步扩展
        } catch (IOException e) {
            System.err.println("读取 Word 文件时发生错误: " + e.getMessage());
        }
        return allCharacters;
    }


    // 匹配数据
    public static Map<String, String> matchData(List<String> columnData, List<Character> allCharacters) {
        Map<String, String> matchedData = new HashMap<>();
        for (String data : columnData) {
            int length = data.length();
            // 遍历字符串中的每一组连续两个字符
            for (int i = 0; i < length - 2; i++) {
                char firstChar = data.charAt(i);
                char secondChar = data.charAt(i + 1);
                char thirdChar = data.charAt(i + 2);
                // 遍历 Word 文件字符列表，检查是否有连续的匹配
                for (int j = 0; j < allCharacters.size() - 2; j++) {
                    if (allCharacters.get(j) == firstChar && allCharacters.get(j + 1) == secondChar && allCharacters.get(j + 2) == thirdChar) {
                        String matchInfo = "匹配到的字符: " + firstChar + secondChar + thirdChar + "--------" + printSurroundingCharacters(allCharacters, j);
                        matchedData.put(data, matchInfo);
                        break;
                    }
                }
                if (matchedData.containsKey(data)) {
                    break;
                }
            }
        }
        return matchedData;
    }

    // 打印匹配到的三个字符前后十个字符
    private static String printSurroundingCharacters(List<Character> allCharacters, int matchIndex) {
        int startIndex = Math.max(0, matchIndex - 10);
        int endIndex = Math.min(allCharacters.size(), matchIndex + 13);

        StringBuilder sb = new StringBuilder();
        sb.append("\n匹配到的上下文: ");
        for (int i = startIndex; i < endIndex; i++) {
            sb.append( allCharacters.get(i));
        }
        System.out.println(sb.toString());
        return String.valueOf(sb);
    }

    public static void main(String[] args) {
        String filePath = "C:\\Users\\WH\\Desktop\\yikData\\副本基层卫生处指标调研表_0221_copy.xlsx";
        String targetFilePath = "C:\\Users\\WH\\Desktop\\yikData\\数据集标准20250220(1)\\苏州市医疗健康大数据中心数据集规范-职业健康----20250123.docx";
        String columnName = "指标名称"; // 替换为实际的列名
        try {
            // 读取指定列的数据
            List<String> columnData = readColumnFromXlsx(filePath, columnName);
            columnData.forEach(System.out::println);
            System.out.println(columnData.size());

            // 获取另一个 Word 文件中的所有字符
            List<Character> allCharacters = getAllCharactersFromWord(targetFilePath);
            // 匹配数据
            Map<String, String> matchedData = matchData(columnData, allCharacters);

            // 写入匹配结果到原 XLSX 文件
            try (FileInputStream fis = new FileInputStream(new File(filePath));
                 Workbook workbook = new XSSFWorkbook(fis)) {
                Sheet sheet = workbook.getSheetAt(0);
                Row headerRow = sheet.getRow(0);
                int lastColumnIndex = headerRow.getLastCellNum();
                Cell headerCell = headerRow.createCell(lastColumnIndex);
                headerCell.setCellValue("匹配结果---职业健康");

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (row != null) {
                        Cell cell = row.getCell(findColumnIndex(headerRow, columnName));
                        if (cell != null && cell.getCellType() == CellType.STRING) {
                            String data = cell.getStringCellValue();
                            Cell resultCell = row.createCell(lastColumnIndex);
                            if (matchedData.containsKey(data)) {
                                resultCell.setCellValue(matchedData.get(data));
                            } else {
                                resultCell.setCellValue("未匹配到");
                            }
                        }
                    }
                }

                try (FileOutputStream fos = new FileOutputStream(new File(filePath))) {
                    workbook.write(fos);
                }
            }

            System.out.println("匹配到的数据数量: " + matchedData.size());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static int findColumnIndex(Row headerRow, String columnName) {
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            Cell cell = headerRow.getCell(i);
            if (cell != null && cell.getCellType() == CellType.STRING && cell.getStringCellValue().equals(columnName)) {
                return i;
            }
        }
        return -1;
    }

}